package cn.ijero.contactlist.main

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import cn.ijero.contactlist.R
import cn.ijero.contactlist.database.table.Contact
import cn.ijero.contactlist.databinding.ActivityMainBinding
import com.github.promeg.pinyinhelper.Pinyin
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MainActivity"
    }

    private lateinit var binding: ActivityMainBinding
    private val viewModel by viewModels<MainViewModel>()
    private val contactListAdapter by lazy {
        ContactListAdapter().apply {
            setOnItemClickListener { adater, view, position ->
                selected(position)
            }
        }
    }

    private val indexAdapter by lazy {
        IndexAdapter().apply {
            setOnItemClickListener { adater, view, position ->
                Toast.makeText(context, data[position], Toast.LENGTH_SHORT).show()
                val list = contactListAdapter.data
                val index = list.indexOfFirst { it.name == data[position] }
                if (index != -1) {
                    val layoutManager =
                        binding.recyclerView.layoutManager as LinearLayoutManager
                    layoutManager.scrollToPositionWithOffset(index, 0)
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)

        setContentView(binding.root)

        initView()
        initObserver()
        initData()
    }

    private fun initObserver() {
        lifecycleScope.launch {
            viewModel.contactList.collect {
                // 初始化内容
                val map = hashMapOf<String, MutableList<Contact>>()

                for (itemEntity in it) {
                    val first = itemEntity.name[0]
                    val pinyin = Pinyin.toPinyin(first)
                    Log.d(TAG, "initData: pinyin=$pinyin")
                    val list = map.getOrPut(pinyin[0].toString()) {
                        mutableListOf()
                    }
                    list.add(itemEntity)
                }

                val targetList = mutableListOf<Contact>()

                val keyList = map.keys.map { it }.sorted()
                for (key in keyList) {
                    val list = map[key] ?: continue
                    targetList.add(Contact(null, key))
                    targetList.addAll(list)
                }

                contactListAdapter.setList(targetList)
            }
        }
    }

    private fun initData() {
        viewModel.loadData()
    }

    private fun initView() {
        binding.editText.addTextChangedListener {
            if (it.isNullOrEmpty()) {
                viewModel.loadData()
            }else{
                viewModel.search(it.toString())
            }
        }
        // 初始化index索引
        val split = getString(R.string.words).split("、")
        indexAdapter.setList(split)

        binding.apply {
            indexRecyclerView.apply {
                adapter = indexAdapter
            }
            recyclerView.apply {
                adapter = contactListAdapter
            }
        }
    }

}